package com.shuai.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shuai.common.constant.AuthenticationConstant;
import com.shuai.common.constant.ErrorCode;
import com.shuai.common.exception.BusinessException;
import com.shuai.common.utils.MyJWTUtil;
import com.shuai.user.annotation.LoginStrategyService;
import com.shuai.user.constant.LoginTypeEnum;
import com.shuai.user.domain.entity.User;
import com.shuai.user.domain.request.EmailLoginRequest;
import com.shuai.user.service.EmailService;
import com.shuai.user.service.LoginBaseService;
import com.shuai.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Objects;

@LoginStrategyService
@Service
public class EmailLoginServiceImpl implements LoginBaseService {

    @Autowired
    private EmailService emailService;

    @Autowired
    private UserService userService;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public User login(Object request, HttpServletResponse response) throws Exception {
        EmailLoginRequest loginRequest = (EmailLoginRequest) request;
        if (!emailService.validateEmailCode(loginRequest.getEmail(), loginRequest.getCode())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "验证码错误");
        }
        emailService.removeEmailCode(loginRequest.getEmail());
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getEmail, loginRequest.getEmail());
        User existsUser = userService.getOne(queryWrapper);
        if (Objects.isNull(existsUser)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "当前邮箱未注册");
        }
        this.setLoginState(existsUser, stringRedisTemplate);
        HashMap<String, Object> payload = new HashMap<>();
        // 添加JWT鉴权信息
        payload.put(AuthenticationConstant.PAYLOAD_USERID, existsUser.getId());
        response.setHeader(AuthenticationConstant.AUTHENTICATION_HEADER, MyJWTUtil.createJWT(payload));
        return existsUser;
    }

    @Override
    public LoginTypeEnum getLoginEnumType() {
        return LoginTypeEnum.EmailLogin;
    }
}
